package com.example.epidemic_assistant.mqtt;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.epidemic_assistant.event.MqttGetDataEvent;
import com.example.epidemic_assistant.event.MqttShowToastEvent;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Mqtt连接
 */
public class MqttConnectManager {

    public static final String TAG = "MqttConnectManager";

    private MqttClient client;
    private MqttConnectOptions options;
    public String HOST = "tcp://test.ranye-iot.net:1883";//服务器地址（协议+地址+端口号）
    public static String RESPONSE_TOPIC = "temperature/upload";//响应主题 - 接收到测量温度
    public static String PUBLISH_TOPIC_POLICE = "temperature/download";//发布主题 - 报警温度

    public String CLIENTID = "EpidemicAssistant";  //客户端ID

    private ScheduledExecutorService scheduler;
    private Handler handler;


    private static volatile MqttConnectManager sInstance;

    public static MqttConnectManager getInstance() {
        if (sInstance == null) {
            synchronized (MqttConnectManager.class) {
                if (sInstance == null) {
                    sInstance = new MqttConnectManager();
                }
            }
        }
        return sInstance;
    }

    private MqttConnectManager() {
        mqttInit();
    }

    private void mqttInit() {
        init();
        startReconnect();
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                int code = msg.what;
                Log.d(TAG, "code->" + code);
                if (code == 3) {
                    String message = msg.obj.toString();
                    Log.d(TAG, "message->" + message);
                    EventBus.getDefault().post(new MqttGetDataEvent(message));
                } else if (code == 30) {
                    EventBus.getDefault().post(new MqttShowToastEvent("连接失败"));
                } else if (code == 31) {
                    EventBus.getDefault().post(new MqttShowToastEvent("连接成功"));
                    try {
                        client.subscribe(RESPONSE_TOPIC, 1);
                        client.subscribe(PUBLISH_TOPIC_POLICE, 1);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    private void init() {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(HOST, CLIENTID,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    Log.d(TAG, "connectionLost-->");
                    startReconnect();
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    Log.d(TAG, "deliveryComplete-->" + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message) {
                    //subscribe后得到的消息会执行到这里面
                    Log.d(TAG, "messageArrived-->");
                    Message msg = new Message();
                    //封装message包
                    msg.what = 3;   //收到消息标志位
                    msg.obj = message.toString();
                    //发送messge到handler
                    handler.sendMessage(msg);    // hander 回传
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Mqtt_connect() {
        new Thread(() -> {
            try {
                if (!(client.isConnected()))  //如果还未连接
                {
                    client.connect(options);
                    Message msg = new Message();
                    msg.what = 31;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Message msg = new Message();
                msg.what = 30;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(() -> {
            if (!client.isConnected()) {
                Mqtt_connect();
            }
        }, 0, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    public void publishMessage(String topic, String message2) {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic, message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}
